<?php

namespace app\radar\controller;

use app\ApiRest;
use app\card\model\CardCount;
use app\card\model\ClientInfo;
use app\card\model\Collection;
use app\card\model\User;
use app\card\model\UserFollow;
use app\card\model\UserPhone;
use app\radar\model\RadarAnswer;
use app\radar\model\RadarCard;
use app\radar\model\RadarCount;
use app\radar\model\RadarFollow;
use app\radar\model\RadarLabel;
use app\radar\model\RadarMessage;
use app\radar\model\RadarOrder;
use app\radar\model\RadarQuestionnaire;
use app\radar\model\RadarStart;
use app\radar\model\RadarUserLabel;
use app\radar\model\RadarUserMark;
use think\App;
use think\facade\Db;

class Index extends ApiRest
{
    protected $modelCount;
    protected $modelCard;

    // 继承 验证用户登陆
    public function __construct ( App $app )
    {
        parent::__construct( $app );
        $this->modelCount = new RadarCount();
        $this->modelCard  = new RadarCard();
        //判断是否是员工
        $user = longbingGetUser($this->getUserId() ,$this->_uniacid);
        $user_info = longbingGetUserInfo($this->getUserId() ,$this->_uniacid);
        //不需要员工权限的接口
        $dont_need_check_actions = ['reportDuration' ,'reportData'];
        if((empty($user['is_staff']) || empty($user_info) || empty($user_info['is_staff'])) && !in_array($this->request->action(), $dont_need_check_actions))
        {
            echo json_encode($this->getErrorData(lang('you are not staff') ,403));
            die;
        }
    }

    /**
     * @Purpose: 员工端雷达列表
     *
     * @Method: GET
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function radarList ()
    {
        $page   = isset( $this->_param[ 'page' ] ) ? $this->_param[ 'page' ] : 1;

        $userId = $this->getUserId();

        $data   = $this->modelCount->radarList( [ [ 'a.to_uid', '=', $userId ] ,['a.user_id' , '<>', $userId]], $page );


        if ( $page == 1 )
        {
            $ids = [];
            foreach ( $data[ 'data' ] as $index => $item )
            {
                array_push( $ids, $item[ 'id' ] );
            }
            //  未读雷达消息数量
            //  By.jingshuixian 有什么用呢?
            $number                 = $this->modelCount->unreadNumber( $userId );
            $data[ 'unreadNumber' ] = $number;
        }

        $data[ 'data' ] = formatDefaultImage( $data[ 'data' ], 'avatarUrl', 'avatar', $this->defaultImage );
        //删除多余不要的字段 可以减少 1秒耗时
        $data['data'] = longbing_array_columns($data['data'],['id','file_page','user_id','nickName','avatarUrl','phone','share_str','radar_arr','intention','radar_group','radar_time','is_staff','remark_name']);

        return $this->success( $data );
    }

    /**
     * @Purpose: 将客户设置为意向客户
     *
     * @Method: POST
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function radarIntention ()
    {
        $userId = $this->getUserId();

        $verify = [ 'client_id' => 'required' ];

        $params = lbGetParamVerify( $this->_input, $verify );
        if(in_array($userId, [$params['client_id']])) return $this->success( [] );
        $collection = Collection::where( [ [ 'uid', '=', $params[ 'client_id' ] ], [ 'to_uid', '=', $userId ] ] )
            ->find();


        if ( empty($collection)||$collection==NULL )
        {
            return $this->error( 'data not found', 402 );
        }
//        dump($collection);exit;
//        Collection::where(['id'=>$collection->id])->update(['intention'=>1]);
        $collection->intention = 1;
        $collection->save();

        return $this->success( [] );
    }

    /**
     * @Purpose: 员工端雷达线索列表
     *
     * @Param: $order number 排序方式 1 = 意向度 其他 = 最后访问时间
     *
     * @Method: GET
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function radarClue ()
    {
        $userId = $this->getUserId();
        $page   = isset( $this->_param[ 'page' ] ) ? $this->_param[ 'page' ] : 1;

        $verify = [ 'order' => 0, 'is_list' => 0 ];

        $params = lbGetParamVerify( $this->_param, $verify );

        $where   = [ [ 'a.to_uid', '=', $userId ] ];
        $where[] = [ 'a.uid', '<>', $userId ];


        if ( $params[ 'is_list' ] != 1 )
        {
            $where[] = [ 'a.intention', '<>', 1 ];
        }
        else
        {
            $where[] = [ 'a.intention', '=', 1 ];
        }

        $order = [ 'field' => 'b_time', 'way' => 'desc' ];

        if ( $params[ 'order' ] == 1 )
        {
            $order = [ 'field' => 'a.rate', 'way' => 'desc' ];
        }

        if ( $params[ 'order' ] == 2 )
        {
            $order = [ 'field' => 'a.update_time', 'way' => 'desc' ];
        }
        $data = $this->handleClientList( $where, $order, $page, $params, $userId );

        //  处理图片默认数据
        $data[ 'data' ] = formatDefaultImage( $data[ 'data' ], 'avatarUrl', 'avatar', $this->defaultImage );

        return $this->success( $data );
    }

    /**
     * @Purpose: 员工端雷达访客详情
     *
     * @Method: POST
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function clientDetail ()
    {
        $userId = $this->getUserId();

        $verify = [ 'client_id' => 'required','staff_id'=>0 ,'page'=>1];

        $params = lbGetParamVerify( $this->_param, $verify );
        if(!empty($params['staff_id'])&&$params['staff_id'] !=0){
            $userId = $params['staff_id'];
        }

        $data = User::alias( 'a' )
            ->field( [ 'a.id', 'a.nickName', 'a.avatarUrl', 'a.import', 'b.rate', 'b.is_auto', 'b.from_uid', 'b.is_qr',
                    'b.is_group', 'b.type as c_type', 'b.target_id', 'b.openGId', 'b.handover_id', 'b.handover_name',
                    'b.intention', 'c.phone', 'a.gender' ,'d.status as is_start']
            )
            ->leftJoin( 'longbing_card_collection b', 'a.id = b.uid && b.to_uid = ' . $userId )
            ->leftJoin( 'longbing_card_user_phone c', 'a.id = c.user_id')
            ->leftJoin('longbing_card_start d' ,'d.user_id = ' . $params[ 'client_id' ] . ' && d.staff_id = ' . $userId)

            ->where( [ [ 'a.id', '=', $params[ 'client_id' ] ] ] )
            ->find();

        if ( !$data )
        {
            return $this->error( lang('data not found'), 402 );
        }
        if(!isset($data['is_start']) || empty($data['is_start'])) $data['is_start'] = 0;

        $data = $data->toArray();
        $data = formatDefaultImage( $data, 'avatarUrl', 'avatar', $this->defaultImage );

        if ( $data[ 'phone' ] === null )
        {
            $data[ 'phone' ] = '';
        }

        $detail = ClientInfo::where( [ [ 'user_id', '=', $params[ 'client_id' ] ], [ 'staff_id', '=', $userId ] ] )
            ->find();
        if ( !$detail )
        {
            $time   = time();
            $detail = ClientInfo::create( [ 'name'     => '', 'sex' => '', 'user_id' => $params[ 'client_id' ],
                    'staff_id' => $userId, 'phone' => '', 'email' => '', 'company' => '',
                    'position' => '', 'address' => '', 'birthday' => '', 'is_mask' => 0, 'remark' => '',
                    'uniacid'  => $this->_uniacid, 'create_time' => $time, 'update_time' => $time,
                    'area'     => '' ]
            );
        }

        $detail = $detail->toArray();

        if ( isset( $detail[ 'area' ] ) && $detail[ 'area' ] )
        {
            $detail[ 'area' ] = explode( ',', $detail[ 'area' ] );
        }

        //  处理用户来源
        $tmp = lbHandelRadarSource( [ $data ] );

        $data = $tmp[ 0 ];

        $data[ 'staff_edit' ] = $detail;

        $radar_list                = $this->modelCount->radarList( [ [ 'a.to_uid', '=', $userId ], [ 'user_id', '=',
            $params[ 'client_id' ] ] ], $params[ 'page' ]
        );


        if(!empty($data) && empty($data['rate'])) $data['rate'] = 5;
        $radar_list[ 'user_info' ] = $data;

        //  跟进记录
        $radar_list[ 'follow_info' ] = [];
        if ( $data[ 'intention' ] )
        {
            $radar_list[ 'follow_info' ] = UserFollow::alias( 'a' )
                ->leftJoin( 'longbing_card_user_info e', 'a.staff_id = e.fans_id' )
                ->leftJoin( 'longbing_card_user f', 'e.fans_id = f.id ')
                ->field( [ 'a.content', 'a.create_time' ,'e.name','e.avatar','f.nickName','f.avatarUrl'] )
                ->where( [ [ 'a.user_id', '=', $params[ 'client_id' ] ],
                        [ 'a.staff_id', '=', $userId ] ]
                )
                ->order( 'a.id', 'desc' )
                ->limit( 3 )
                ->select();

            $radar_list[ 'follow_info' ] = lbHandelRadarDate( $radar_list[ 'follow_info' ], 'create_time' );
            foreach ( $radar_list[ 'follow_info' ] as $index => $item )
            {
                $radar_list[ 'follow_info' ][ $index ][ 'create_time' ] = date( 'Y-m-d H:i', $item[ 'create_time' ] );
                if(!$item['name']){
                    $radar_list[ 'follow_info' ][ $index ][ 'name' ] = lbUserName($userId);
                }
                if(!$item['avatar']){
                    $radar_list[ 'follow_info' ][ $index ][ 'avatar' ] = lbUserAvatar($userId);
                }
            }
        }

        return $this->success( $radar_list );
    }

    /**
     * @Purpose: 员工端雷达访客AI分析
     *
     * @Method: GET
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function clientAiAnalysis ()
    {
        $userId = $this->getUserId();

        $verify = [ 'client_id' => 'required','staff_id'=>0 ];

        $params = lbGetParamVerify( $this->_param, $verify );
        if(!empty($params['staff_id'])&&$params['staff_id'] !=0){
            $userId = $params['staff_id'];
        }

        //  客户兴趣占比
        $data[ 'interest' ] = $this->modelCount->interest( $params[ 'client_id' ], $userId, $this->_uniacid );
        //  近15日客户活跃度
        list ( $data[ 'active' ], $data[ 'active_max' ] ) = $this->modelCount->active( $params[ 'client_id' ], $userId, $this->_uniacid );
        //  客户与我的互动
        $data[ 'interaction' ] = $this->modelCount->interaction( $params[ 'client_id' ], $userId, $this->_uniacid );

        return $this->success( $data );
    }

    /**
     * @Purpose: 小程序端雷达上报
     *
     * @Method: POST
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function reportData ()
    {

        try{
            $userId = $this->getUserId();
            $params = $this->_input;
//            dump($params);exit;


            //$verify = [ 'staff_id' => 'required', 'type' => 'required', 'sign' => 'required', 'scene' => '' ,'target' => ''];
            //$params = lbGetParamVerify( $this->_input, $verify );

            if(empty($params[ 'staff_id' ]) or $params[ 'staff_id' ] == 0 ){
                return $this->success( [  'status' => 'staff_id error'  ,'staff_id'=> $params[ 'staff_id' ]] );
            }


            if (in_array($params[ 'staff_id' ], [$userId]))
            {
                return $this->success( [] );
            }
            $modelCount = new RadarCount();

            $data = array(

                'user_id' => $userId,

                'to_uid'  => $params[ 'staff_id' ],

                'type'    => $params[ 'type' ],

                'sign'    => $params[ 'sign' ],

                'scene'   => intval( $params[ 'scene' ]),

                'uniacid' => $this->_uniacid
            );

            if(isset($params['target'])) $data['target'] = $params['target'];
            //时长
            // if(isset($params['time_long'])) $data['time_long'] = $params['time_long'];

            $result = $modelCount->createCount( $data );

            if ( $result === false )
            {
                return $this->success( [] );
            }
            //发送服务通知
            if(!empty($modelCount->id)){
                $push_data = array(
                    'action'   => 'SendWxServiceNotice',
                    'event'    => 'SendWxServiceNotice',
                    'count_id' => $modelCount->id
                );
                publisher(json_encode($push_data ,true) ,5000);
            }

            //更新雷达意向度

            longbing_radar_update_rate($userId , $params[ 'staff_id' ],$this->_uniacid);

            return $this->success( [ 'id' => $modelCount->id ] );

        }catch (\Exception $e){

            if(APP_DEBUG){
                throw $e ;
            }else{
                return $this->success( ['hava error'] );
            }

        }



    }

    /**
     * @Purpose: 小程序端雷达上报时长
     *
     * @Method: POST
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function reportDuration ()
    {
        $userId = $this->getUserId();

        $verify = [ 'id' => 'required' ];

//        $params = lbGetParamVerify( $this->_input, $verify );

        $params =  $this->_input;

        $info   = $this->modelCount->find( $params[ 'id' ] );
        if ( !$info )
        {
            $this->error( 'report fail', 400 );
        }

        $info->duration += time() - $info->update_time;

        if(isset($params['total_page'])&&isset($params['read_page'])){

            $info->total_page = $params['total_page'];

            $info->read_page  = $params['read_page'];

        }

        $info->save();

        return $this->success( [] );
    }

    /**
     * @Purpose: 编辑客户信息
     *
     * @Method: POST
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function editClientInfo ()
    {
        $userId = $this->getUserId();

        $verify = [ 'client_id' => 'required', 'name' => '', 'sex' => 0, 'phone' => '', 'email' => '', 'company' => '',
            'position'  => '', 'address' => '', 'birthday' => '', 'remark' => '', 'wechat' => '', 'area' => '' ];

        $params = lbGetParamVerify( $this->_input, $verify );

        if(strlen($params['name'])>30){

            return $this->error('备注名过长');
        }

        if ( $params[ 'area' ] )
        {
            $params[ 'area' ] = implode( ',', $params[ 'area' ] );
        }

        $client_id = $params[ 'client_id' ];

        unset( $params[ 'client_id' ] );

        $result = ClientInfo::where( [ [ 'user_id', '=', $client_id ], [ 'staff_id', '=', $userId ] ] )
            ->update( $params );

        if ( $result === false )
        {
            $this->error( 'edit fail', 402 );
        }
        return $this->success( [] );
    }

    /**
     * @Purpose: 添加客户跟进记录
     *
     * @Method: POST
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function addFollow ()
    {
        $userId = $this->getUserId();

        $verify = [ 'client_id' => 'required', 'content' => 'required', 'type' => 1 ];

        $params = lbGetParamVerify( $this->_input, $verify );

        $data = [ 'user_id' => $params[ 'client_id' ], 'staff_id' => $userId, 'content' => $params[ 'content' ],
            'type'    => $params[ 'type' ] ,'uniacid' => $this->_uniacid];


        $modelFollow = new RadarFollow();

        $result      = $modelFollow->createRow( $data );

        if($result)
        {
            $collection_model = new Collection();
            $collection = $collection_model->getCollection(['uid' => $params[ 'client_id' ] ,'to_uid' => $userId]);
            if(!empty($collection)) $collection_model->updateCollection(['uid' => $params[ 'client_id' ] ,'to_uid' => $userId] ,[]);

            $RadarUserMark = new RadarUserMark();

            $mark = $RadarUserMark->where(['user_id' => $params[ 'client_id' ], 'staff_id' => $userId,'status'=>1])->find();

            if(empty($mark)){

                RadarUserMark::create( [ 'user_id' => $params[ 'client_id' ], 'staff_id' => $userId, 'mark' => 1,
                        'status'  => 1, 'uniacid' => $this->_uniacid ]
                );

            }



        }
        if ( $result === false )
        {
            $this->error( 'insert fail', 402 );
        }
        return $this->success( [] );
    }

    /**
     * @Purpose: 添加客户标签
     *
     * @Method: POST
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function addLabels ()
    {
        $userId = $this->getUserId();

        $verify = [ 'client_id' => 'required', 'content' => 'required' ];

        $params = lbGetParamVerify( $this->_input, $verify );

        $modelLabel     = new RadarLabel();
        $modelUserLabel = new RadarUserLabel();

        $modelUserLabel->where( [ [ 'user_id', '=', $params[ 'client_id' ] ], [ 'staff_id', '=', $userId ] ] )
            ->delete();

        foreach ( $params[ 'content' ] as $index => $item )
        {
            $label = $modelLabel->where( [ [ 'name', '=', $item ] ] )
                ->find();
            if ( !$label )
            {
                $label = $modelLabel->create( [ 'name' => $item, 'status' => 1, 'uniacid' => $this->_uniacid ] );
            }

            $modelUserLabel->create( [ 'user_id'  => $params[ 'client_id' ], 'status' => 1, 'uniacid' => $this->_uniacid,
                    'staff_id' => $userId, 'label_id' => $label[ 'id' ] ]
            );
        }

        return $this->success( [] );
    }

    /**
     * @Purpose: 客户标签记录
     *
     * @Method: GET
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function labelList ()
    {
        $userId = $this->getUserId();

        $verify = [ 'client_id' => 'required','staff_id'=>0 ];

        $params = lbGetParamVerify( $this->_param, $verify );
        if(!empty($params['staff_id'])&&$params['staff_id'] !=0){
            $userId = $params['staff_id'];
        }
        $modelUserLabel = new RadarUserLabel();

        $userLabelList = $modelUserLabel->alias( 'a' )
            ->field( [ 'a.id', 'b.name' ] )
            ->join( 'longbing_card_label b', 'a.label_id = b.id' )
            ->where( [ [ 'a.user_id', '=', $params[ 'client_id' ] ], [ 'a.staff_id', '=', $userId ] ])
            ->select()
            ->toArray();

        $myLabelList = $modelUserLabel->alias( 'a' )
            ->field( [ 'b.name' ] )
            ->join( 'longbing_card_label b', 'a.label_id = b.id' )
            ->where( [ [ 'a.staff_id', '=', $userId ] ] )
            ->group( 'a.label_id' )
            ->select()
            ->toArray();


        foreach ( $myLabelList as $index => $item )
        {
            $myLabelList[ $index ][ 'selected' ] = 0;
            foreach ( $userLabelList as $index2 => $item2 )
            {
                if ( $item2[ 'name' ] == $item[ 'name' ] )
                {
                    $myLabelList[ $index ][ 'selected' ] = 1;
                    break;
                }
            }
        }

        $data[ 'userLabelList' ] = $userLabelList;
        $data[ 'myLabelList' ]   = $myLabelList;

        $check = RadarUserMark::where( [ [ 'user_id', '=', $params[ 'client_id' ] ], [ 'staff_id', '=', $userId ] ] )
            ->find();


        $data[ 'mark' ] = $check ? $check[ 'mark' ] : 0;

        return $this->success( $data );
    }

    /**
     * @Purpose: 搜索客户
     *
     * @Method: POST
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function searchClient ()
    {
        $userId = $this->getUserId();

        $verify = [ 'keyword' => 'required', 'is_list' => 0 ];

        $params = lbGetParamVerify( $this->_input, $verify );

        $keyword       = '%' . $params[ 'keyword' ] . '%';
        $client_id_arr = [];

        //  搜索标签
        $list = RadarUserLabel::alias( 'a' )
            ->field( [ 'a.user_id' ] )
            ->join( 'longbing_card_label b', 'a.label_id = b.id' )
            ->where( [ [ 'b.name', 'like', $keyword ], [ 'a.staff_id', '=', $userId ] ] )
            ->select()
            ->toArray();
        foreach ( $list as $index => $item )
        {
            array_push( $client_id_arr, $item[ 'user_id' ] );
        }

        //  搜索员工给客户的备注名
        $list = ClientInfo::field( [ 'user_id' ] )
            ->where( [ [ 'name', 'like', $keyword ], [ 'staff_id', '=', $userId ] ] )
            ->select()
            ->toArray();
        foreach ( $list as $index => $item )
        {
            array_push( $client_id_arr, $item[ 'user_id' ] );
        }

        //  搜索用户微信昵称
        $list = Collection::alias( 'a' )
            ->field( [ 'a.uid as user_id' ] )
            ->join( 'longbing_card_user b', 'a.uid = b.id' )
            ->where( [ [ 'b.nickName', 'like', $keyword ], [ 'a.to_uid', '=', $userId ] ] )
            ->select()
            ->toArray();

        foreach ( $list as $index => $item )
        {
            array_push( $client_id_arr, $item[ 'user_id' ] );
        }

        $client_id_arr = array_unique( $client_id_arr );


        $page = isset( $this->_param[ 'page' ] ) ? $this->_param[ 'page' ] : 1;


        $where = [ [ 'a.to_uid', '=', $userId ] ];

        $where[] = [ 'a.uid', 'in', $client_id_arr ];


        $order = [ 'field' => 'b_time', 'way' => 'desc' ];

        $data = $this->handleClientList( $where, $order, $page, $params, $userId );

        return $this->success( $data );
    }

    /**
     * @Purpose: 处理客户列表
     *
     * @Method: protected
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    protected function handleClientList ( $where, $order, $page, $params, $userId )
    {
        $data = Collection::alias( 'a' )
            ->field( [ 'a.*', 'b.id as b_id', 'b.create_time', 'max(b.create_time) as b_time',
                    'count(b.id) as b_count', 'c.nickName', 'c.avatarUrl', 'c.avatarUrl', 'c.import',
                    'c.gender','c.is_staff' ]
            )
            ->where( $where )
            ->leftJoin( 'longbing_card_count b', 'a.uid = b.user_id && a.to_uid = b.to_uid' )
            ->join( 'longbing_card_user c', 'a.uid = c.id' )
            ->order( $order[ 'field' ], $order[ 'way' ] )
            ->group( 'a.uid, a.to_uid' )
            ->paginate( [ 'list_rows' => 10, 'page' => $page ] )
            ->toArray();

        foreach ($data['data'] as $key => $val)
        {
            if(!isset($val['b_time']) || empty($val['b_time'])) $data['data'][$key]['b_time'] = $val['create_time'];

            if(empty($data['data'][$key]['b_time'])) $data['data'][$key]['b_time'] = $val['update_time'];

            $dis = [

                'user_id'  =>  $val['uid'],

                'staff_id' =>  $val['to_uid'],
            ];

            $data['data'][$key]['remark_name'] = Db::name('longbing_card_client_info')->where($dis)->value('name');
        }
        //  处理雷达展示日期
        $data[ 'data' ] = lbHandelRadarDate( $data[ 'data' ], 'b_time' );
        //  处理用户来源
        $data[ 'data' ] = lbHandelRadarSource( $data[ 'data' ] );

        //  client_source 用户来源 1 = 微信小程序 2 = 百度小程序 3 = 支付宝小程序 4 = 抖音小程序
        //  查询手机号
        $tmpArr = [];
        foreach ( $data[ 'data' ] as $index => $item )
        {
            $data[ 'data' ][ $index ][ 'phone' ]         = '';
            $data[ 'data' ][ $index ][ 'client_source' ] = 1;
            array_push( $tmpArr, $item[ 'uid' ] );

            // 客户列表相关数据
            if ( $params[ 'is_list' ] == 1 )
            {
                //  给客户打的标签
                $labelList = RadarUserLabel::alias( 'a' )
                    ->field( [ 'b.name' ] )
                    ->join( 'longbing_card_label b', 'a.label_id = b.id' )
                    // 注意这里的表明中的label和字段名label_id不一样，因为字段名取名取错了
                    ->where( [ [ 'a.staff_id', '=', $userId ], [ 'a.user_id', '=', $item[ 'uid' ] ],
                            [ 'a.status', '=', 1 ] ]
                    )
                    ->limit( 4 )
                    ->select()
                    ->toArray();

                $data[ 'data' ][ $index ][ 'labelList' ]  = $labelList;
                $data[ 'data' ][ $index ][ 'labelCount' ] = RadarUserLabel::alias( 'a' )
                    ->field( [ 'b.name' ] )
                    ->join( 'longbing_card_label b', 'a.label_id = b.id' )
                    // 注意这里的表明中的label和字段名label_id不一样，因为字段名取名取错了
                    ->where( [ [ 'a.staff_id', '=', $userId ],
                            [ 'a.user_id', '=', $item[ 'uid' ] ],
                            [ 'a.status', '=', 1 ] ]
                    )
                    ->count();

                //  聊天数量
                $map1         = [ [ 'user_id', '=', $item[ 'uid' ] ], [ 'target_id', '=', $userId ] ];
                $map2         = [ [ 'target_id', '=', $item[ 'uid' ] ], [ 'user_id', '=', $userId ] ];
                $messageCount = RadarMessage::whereOr( [ $map1, $map2 ] )
                    ->count();

                $data[ 'data' ][ $index ][ 'messageCount' ] = $messageCount;

                //  商城订单
                $orderCount                               = RadarOrder::where( [ [ 'pay_status', '=', 1 ],
                        [ 'order_status', '<>', 1 ],
                        [ 'user_id', '=', $item[ 'uid' ] ],
                        [ 'to_uid', '=', $userId ],
                        [ 'refund_status', '=', 0 ] ]
                )
                    ->count();
                $data[ 'data' ][ $index ][ 'orderCount' ] = $orderCount;

                //  通话数量
                $phoneCount = CardCount::where( [ [ 'user_id', '=', $item[ 'uid' ] ], [ 'to_uid', '=', $userId ],
                        [ 'sign', '=', 'copy' ], [ 'type', 'in', [ 2, 3, 11 ] ] ]
                )
                    ->count();

                $data[ 'data' ][ $index ][ 'phoneCount' ] = $phoneCount;
            }

        }
        if ( !empty( $tmpArr ) )
        {
            $tmpArr = array_unique( $tmpArr );

            $list = UserPhone::where( [ [ 'user_id', 'in', $tmpArr ] ] )
                ->field( [ 'user_id', 'phone' ] )
                ->select()
                ->toArray();

            $markList = RadarUserMark::where( [ [ 'user_id', 'in', $tmpArr ] ,['staff_id' ,'=' ,$userId]] )
                ->field( [ 'user_id', 'mark' ] )
                ->select()
                ->toArray();

            $tmpArr     = [];
            $tmpArrMark = [];

            foreach ( $list as $index => $item )
            {
                $tmpArr[ $item[ 'user_id' ] ] = $item[ 'phone' ];
            }

            foreach ( $markList as $index => $item )
            {
                $tmpArrMark[ $item[ 'user_id' ] ] = $item[ 'mark' ];
            }

            foreach ( $data[ 'data' ] as $index => $item )
            {
                $data[ 'data' ][ $index ][ 'mark' ] = 0;

                if ( isset( $tmpArr[ $item[ 'uid' ] ] ) )
                {
                    $data[ 'data' ][ $index ][ 'phone' ] = $tmpArr[ $item[ 'uid' ] ];
                }
                $data[ 'data' ][ $index ][ 'mark' ] = 0;
                if ( isset( $tmpArrMark[ $item[ 'uid' ] ] ) )
                {
                    $data[ 'data' ][ $index ][ 'mark' ] = $tmpArrMark[ $item[ 'uid' ] ];
                    if ( $tmpArrMark[ $item[ 'uid' ] ] == 2 && isset( $data[ 'data' ][ $index ][ 'labelCount' ] ) )
                    {
                        $data[ 'data' ][ $index ][ 'labelCount' ] += 1;
                    }
                }
            }
        }

        $data[ 'data' ] = formatDefaultImage( $data[ 'data' ], 'avatarUrl', 'avatar', $this->defaultImage );

        return $data;
    }

    /**
     * @Purpose: 客户跟进记录列表
     *
     * @Method: GET
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function followList ()
    {
        $userId = $this->getUserId();

        $verify = [ 'client_id' => 'required', 'page' => 1,'staff_id'=>0 ];

        $params = lbGetParamVerify( $this->_param, $verify );
        if(!empty($params['staff_id'])&&$params['staff_id'] !=0){
            $userId = $params['staff_id'];
        }
        $modelFollow = new RadarFollow();


        $data = $modelFollow->alias('a')->where( [ [ 'a.user_id', '=', $params[ 'client_id' ] ], [ 'a.staff_id', '=', $userId ] ] )
            ->leftJoin( 'longbing_card_user_info e', 'a.staff_id = e.fans_id' )
            ->leftJoin( 'longbing_card_user f', 'e.fans_id = f.id ')
            ->field(['a.*','e.name','e.avatar','f.nickName','f.avatarUrl','f.id as staff_user_id'])
            ->order( [ 'a.id' => 'desc' ] )
            ->paginate( [ 'list_rows' => 20, 'page' => $params[ 'page' ] ] )->each(function ($val){

                if(!$val['name']){

                    $val['name'] = lbUserName($val['staff_user_id']);
                }
                if(!$val['avatar']){

                    $val['avatar'] = lbUserAvatar($val['staff_user_id']);
                }
                return $val;
            })
            ->toArray();


        $data[ 'data' ] = handleTimes( $data[ 'data' ], 'create_time', 'Y-m-d H:i' );

        return $this->success( $data );
    }

    /**
     * @Purpose: 屏蔽 / 取消屏蔽客户
     *
     * @Method: POST
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function shieldClient ()
    {
        $userId = $this->getUserId();

        $verify = [ 'client_id' => 'required' ];

        $params = lbGetParamVerify( $this->_param, $verify );

        $data = ClientInfo::where( [ [ 'user_id', '=', $params[ 'client_id' ] ], [ 'staff_id', '=', $userId ] ] )
            ->find();

        if ( !$data )
        {
            $this->error( 'client info not found' );
        }

        if ( $data->is_mask == 0 )
        {
            $data->is_mask = 1;
        }
        else
        {
            $data->is_mask = 0;
        }

        $data->save();

        return $this->success( $data );
    }

    /**
     * @Purpose: 客户问卷内容
     *
     * @Method: GET
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function questions ()
    {
        $userId = $this->getUserId();

        $verify = [ 'client_id' => 'required' ];

        $params = lbGetParamVerify( $this->_param, $verify );

        $model = new RadarQuestionnaire();

        $data = $model->getQuestionnaireInfo( $params[ 'client_id' ], $userId, $this->_uniacid );

        return $this->success( $data );
    }

    /**
     * @Purpose: 上报客户问卷内容
     *
     * @Method: POST
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function subQuestions ()
    {
        $userId = $this->getUserId();

        $verify = [ 'client_id' => 'required', 'question_ids' => '', 'answers' => '' ];

        $params = lbGetParamVerify( $this->_param, $verify );

        $modelAnswer = new RadarAnswer();
        $modelAnswer->where( [ [ 'user_id', '=', $params[ 'client_id' ] ], [ 'staff_id', '=', $userId ],
                [ 'q_id', 'in', $params[ 'question_ids' ] ] ]
        )
            ->delete();

        $data = [];

        foreach ( $params[ 'question_ids' ] as $index => $item )
        {
            if ( !$params[ 'answers' ][ $index ] )
            {
                continue;
            }

            $tmp = [ 'user_id' => $params[ 'client_id' ], 'staff_id' => $userId, 'answer' => $params[ 'answers' ][ $index ],
                'uniacid' => $this->_uniacid, 'status' => 1, 'q_id' => $item ];

            array_push( $data, $tmp );
        }

        if ( !empty( $data ) )
        {
            $modelAnswer->saveAll( $data );
        }

        return $this->success( [] );
    }

    /**
     * @Purpose: 标签
     *
     * @Method GET
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function labels ()
    {
        $userId = $this->getUserId();

        //  客户标签
        $info = RadarUserLabel::alias( 'a' )
            ->field( [ 'b.name', 'count(a.id) as number', 'a.label_id' ] )
            ->join( 'longbing_card_label b', 'a.label_id = b.id' )
            ->group( 'a.label_id' )
            ->where( [ [ 'a.staff_id', '=', $userId ], [ 'a.status', '=', 1 ]] )
            ->select()
            ->toArray();

        $data[ 'labels' ] = $info;

        //  星标客户
        $info            = RadarStart::where( [ [ 'staff_id', '=', $userId ] ,['user_id' ,'<>' ,$userId], [ 'status', '=', 1 ]] )
            ->count();
        $data[ 'start' ] = $info;

        //  已成交客户
        $info           = RadarUserMark::where( [ [ 'staff_id', '=', $userId ],['user_id' ,'<>' ,$userId] ,[ 'status', '=', 1 ], [ 'mark', '=', 2 ] ] )
            ->count();
        $data[ 'deal' ] = $info;


        return $this->success( $data );
    }

    /**
     * @Purpose: 标签客户列表
     *
     * @Param: $order number 排序方式 1 = 意向度 其他 = 最后访问时间
     *
     * @Method GET
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function labelClientList ()
    {
        $userId = $this->getUserId();

        $verify = [ 'label_id' => 0, 'mark' => 0, 'start' => 0, 'page' => 1, 'order' => 0, 'is_list' => 0 ];

        $params = lbGetParamVerify( $this->_param, $verify );

        //        $where   = [ [ 'a.to_uid', '=', $userId ] ];
        $where   = [ 'a.uid', '<>', $userId ];
        $where[] = [ 'd.staff_id', '=', $userId ];

        $order = [ 'field' => 'b_time', 'way' => 'desc' ];

        if ( $params[ 'order' ] == 1 )
        {
            $order = [ 'field' => 'c.rate', 'way' => 'desc' ];
        }

        //  查询新标客户
        if ( $params[ 'start' ] == 1 )
        {

            $data = RadarStart::alias( 'a' )
                ->field( [ 'd.id as b_id', 'd.create_time', 'max(d.create_time) as b_time',
                        'count(d.id) as b_count', 'b.nickName', 'b.avatarUrl', 'b.avatarUrl', 'b.import',
                        'b.gender', 'c.*' ]
                )
                ->where( [ [ 'a.staff_id', '=', $userId ], [ 'a.status', '=', 1 ] ] )
                ->join( 'longbing_card_user b', 'a.user_id = b.id' )
                ->join( 'longbing_card_collection c', 'a.user_id = c.uid && c.to_uid = a.staff_id' )
                ->join( 'longbing_card_count d', 'a.user_id = d.user_id && a.staff_id = d.to_uid' )
                ->order( $order[ 'field' ], $order[ 'way' ] )
                ->group( 'a.user_id, a.staff_id' )
                ->paginate( [ 'list_rows' => 10, 'page' => $params[ 'page' ] ] )
                ->toArray();

        }
        //  已成交的客户
        else if ( $params[ 'mark' ] == 1 )
        {
            $data = RadarUserMark::alias( 'a' )
                ->field( [ 'd.id as b_id', 'd.create_time', 'max(d.create_time) as b_time',
                        'count(d.id) as b_count', 'b.nickName', 'b.avatarUrl', 'b.avatarUrl', 'b.import',
                        'b.gender', 'c.*' ]
                )
                ->where( [ [ 'a.staff_id', '=', $userId ], [ 'a.user_id', '<>', $userId ],
                        [ 'a.status', '=', 1 ], [ 'mark', '=', 2 ] ]
                )
                ->join( 'longbing_card_user b', 'a.user_id = b.id' )
                ->join( 'longbing_card_collection c', 'a.user_id = c.uid && c.to_uid = a.staff_id' )
                ->join( 'longbing_card_count d', 'a.user_id = d.user_id && a.staff_id = d.to_uid' )
                ->order( $order[ 'field' ], $order[ 'way' ] )
                ->group( 'a.user_id, a.staff_id' )
                ->paginate( [ 'list_rows' => 10, 'page' => $params[ 'page' ] ] )
                ->toArray();

        }
        //  已成交的客户
        else if ( $params[ 'label_id' ] )
        {
            $data = RadarUserLabel::alias( 'a' )
                ->field( [ 'd.id as b_id', 'd.create_time', 'max(d.create_time) as b_time',
                        'count(d.id) as b_count', 'b.nickName', 'b.avatarUrl', 'b.avatarUrl', 'b.import',
                        'b.gender', 'c.*' ]
                )
                ->where( [ [ 'a.staff_id', '=', $userId ], [ 'a.user_id', '<>', $userId ],
                        [ 'a.status', '=', 1 ], [ 'label_id', '=', $params[ 'label_id' ] ] ]
                )
                ->join( 'longbing_card_user b', 'a.user_id = b.id' )
                ->join( 'longbing_card_collection c', 'a.user_id = c.uid && c.to_uid = a.staff_id' )
                ->join( 'longbing_card_count d', 'a.user_id = d.user_id && a.staff_id = d.to_uid' )
                ->order( $order[ 'field' ], $order[ 'way' ] )
                ->group( 'a.user_id, a.staff_id' )
                ->paginate( [ 'list_rows' => 10, 'page' => $params[ 'page' ] ] )
                ->toArray();

        }
        else
        {
            return $this->success( [] );
        }

        //  处理雷达展示日期
        $data[ 'data' ] = lbHandelRadarDate( $data[ 'data' ], 'b_time' );

        //  处理用户来源
        $data[ 'data' ] = lbHandelRadarSource( $data[ 'data' ] );

        //  client_source 用户来源 1 = 微信小程序 2 = 百度小程序 3 = 支付宝小程序 4 = 抖音小程序
        //  查询手机号
        $tmpArr = [];
        foreach ( $data[ 'data' ] as $index => $item )
        {
            $data[ 'data' ][ $index ][ 'phone' ]         = '';
            $data[ 'data' ][ $index ][ 'client_source' ] = 1;


            array_push( $tmpArr, $item[ 'uid' ] );

            // 客户列表相关数据
            if ( $params[ 'is_list' ] == 1 )
            {
                //  给客户打的标签
                $labelList = RadarUserLabel::alias( 'a' )
                    ->field( [ 'b.name' ] )
                    ->join( 'longbing_card_label b', 'a.label_id = b.id' )
                    // 注意这里的表明中的label和字段名label_id不一样，因为字段名取名取错了
                    ->where( [ [ 'a.staff_id', '=', $userId ], [ 'a.user_id', '=', $item[ 'uid' ] ],
                            [ 'a.status', '=', 1 ] ]
                    )
                    ->limit( 4 )
                    ->select()
                    ->toArray();

                $data[ 'data' ][ $index ][ 'labelList' ]  = $labelList;
                $data[ 'data' ][ $index ][ 'labelCount' ] = RadarUserLabel::alias( 'a' )
                    ->field( [ 'b.name' ] )
                    ->join( 'longbing_card_label b', 'a.label_id = b.id' )
                    // 注意这里的表明中的label和字段名label_id不一样，因为字段名取名取错了
                    ->where( [ [ 'a.staff_id', '=', $userId ],
                            [ 'a.user_id', '=', $item[ 'uid' ] ],
                            [ 'a.status', '=', 1 ] ]
                    )
                    ->count();

                //  聊天数量
                $map1         = [ [ 'user_id', '=', $item[ 'uid' ] ], [ 'target_id', '=', $userId ] ];
                $map2         = [ [ 'target_id', '=', $item[ 'uid' ] ], [ 'user_id', '=', $userId ] ];
                $messageCount = RadarMessage::whereOr( [ $map1, $map2 ] )
                    ->count();

                $data[ 'data' ][ $index ][ 'messageCount' ] = $messageCount;

                //  商城订单
                $orderCount                               = RadarOrder::where( [ [ 'pay_status', '=', 1 ],
                        [ 'order_status', '<>', 1 ],
                        [ 'user_id', '=', $item[ 'uid' ] ],
                        [ 'to_uid', '=', $userId ],
                        [ 'refund_status', '=', 0 ] ]
                )
                    ->count();
                $data[ 'data' ][ $index ][ 'orderCount' ] = $orderCount;

                //  通话数量
                $phoneCount = CardCount::where( [ [ 'user_id', '=', $item[ 'uid' ] ], [ 'to_uid', '=', $userId ],
                        [ 'sign', '=', 'copy' ], [ 'type', 'in', [ 2, 3, 11 ] ] ]
                )
                    ->count();

                $data[ 'data' ][ $index ][ 'phoneCount' ] = $phoneCount;
            }

        }
        if ( !empty( $tmpArr ) )
        {
            $tmpArr = array_unique( $tmpArr );

            $list = UserPhone::where( [ [ 'user_id', 'in', $tmpArr ] ] )
                ->field( [ 'user_id', 'phone' ] )
                ->select()
                ->toArray();

            $markList = RadarUserMark::where( [ [ 'user_id', 'in', $tmpArr ] ] )
                ->field( [ 'user_id', 'mark' ] )
                ->select()
                ->toArray();

            $tmpArr     = [];
            $tmpArrMark = [];

            foreach ( $list as $index => $item )
            {
                $tmpArr[ $item[ 'user_id' ] ] = $item[ 'phone' ];
            }

            foreach ( $markList as $index => $item )
            {
                $tmpArrMark[ $item[ 'user_id' ] ] = $item[ 'mark' ];
            }

            foreach ( $data[ 'data' ] as $index => $item )
            {
                if ( isset( $tmpArr[ $item[ 'uid' ] ] ) )
                {
                    $data[ 'data' ][ $index ][ 'phone' ] = $tmpArr[ $item[ 'uid' ] ];
                }

                if ( isset( $tmpArrMark[ $item[ 'uid' ] ] ) )
                {
                    $data[ 'data' ][ $index ][ 'mark' ] = $tmpArrMark[ $item[ 'uid' ] ];
                    if ( $tmpArrMark[ $item[ 'uid' ] ] == 2 && isset( $data[ 'data' ][ $index ][ 'labelCount' ] ) )
                    {
                        $data[ 'data' ][ $index ][ 'labelCount' ] += 1;
                    }
                }
            }
        }

        $data[ 'data' ] = formatDefaultImage( $data[ 'data' ], 'avatarUrl', 'avatar', $this->defaultImage );

        return $this->success( $data );

    }

    /**
     * @Purpose: 将客户设置为成交
     *
     * @Method POST
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function makeDeal ()
    {
        $userId = $this->getUserId();

        $verify = [ 'client_id' => 'required' ];

        $params = lbGetParamVerify( $this->_input, $verify );

        $check = RadarUserMark::where( [ [ 'user_id', '=', $params[ 'client_id' ] ], [ 'staff_id', '=', $userId ] ] )
            ->find();



        if ( !$check )
        {
            $result = RadarUserMark::create( [ 'user_id' => $params[ 'client_id' ], 'staff_id' => $userId, 'mark' => 2,
                    'status'  => 1, 'uniacid' => $this->_uniacid ]
            );

            return $this->success(['mark' => 2 ]);
        }
//        else if ( $check && $check[ 'mark' ] == 1 )
//        {
//            $check->mark = 2;
//            $check->save();
//        }

        $swich_map = [
            1 => 2,
            2 => 1
        ];
        if (isset($swich_map[$check->mark])) {
            $check->mark = $swich_map[$check->mark];
            $check->save();
        }

        return $this->success( ['mark' => $check->mark] );

    }

    /**
     * @Purpose: 编辑标签
     *
     * @Method POST
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function editLabels ()
    {
        $userId = $this->getUserId();

        $verify = [ 'label_id' => 'required', 'title' => 'required' ];

        $params = lbGetParamVerify( $this->_input, $verify );

        $check = RadarLabel::where( [ [ 'name', '=', $params[ 'title' ] ], [ 'uniacid', '=', $this->_uniacid ] ] )
            ->find();

        if ( !$check )
        {
            $check = RadarLabel::create( [ 'name' => $params[ 'title' ], 'uniacid' => $this->_uniacid, 'status' => 1 ] );
        }

        RadarUserLabel::update( [ 'label_id' => $check[ 'id' ] ], [ 'staff_id' => $userId, 'label_id' => $params[ 'label_id' ] ]
        );

        return $this->success( [ 'label_id' => $check[ 'id' ] ] );
    }

    /**
     * @Purpose: 删除标签
     *
     * @Method POST
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function deleteLabels ()
    {
        $userId = $this->getUserId();

        $verify = [ 'label_id' => 'required'];

        $params = lbGetParamVerify( $this->_input, $verify );

        RadarUserLabel::where( [ [ 'label_id', '=', $params[ 'label_id' ] ], [ 'staff_id', '=', $userId ] ] )
            ->delete();

        return $this->success( [] );
    }
    //设置客户星标
    public function setStart()
    {
        //获取员工id
        $staff_id = $this->getUserId();
        //获取客户id
        $verify = [ 'user_id' => 'required' ,'status' => 1];
        $params = lbGetParamVerify( $this->_input, $verify );
        //查看员工数据是否正确
        $staff  = longbingGetUser($staff_id ,$this->_uniacid);
        $staff_info = longbingGetUserInfo($staff_id ,$this->_uniacid);
        if(empty($staff) || empty($staff_info) || empty($staff_info['is_staff']) || empty($staff['is_staff'])) return $this->error(lang('not staff'));
        //查看客户是否正确
        $user   = longbingGetUser($params['user_id'] ,$this->_uniacid);
        if(empty($user)) return $this->error(lang('not customer'));
        //生成星标模型
        $start_model = new RadarStart();
        $result      = $start_model->getStart(['uniacid' => $this->_uniacid ,'user_id' => $params['user_id'] ,'staff_id' => $staff_id]);
        $start_model = new RadarStart();
        if(!empty($result))
        {
            if(!in_array($result['status'] ,[$params['status']]))
            {
                $result = $start_model->updateStart(['id' => $result['id']] ,['status' => $params['status']]);
            }else{
                $result = true;
            }
        }else{
            $result = $start_model->createStart(['uniacid' => $this->_uniacid ,'user_id' => $params['user_id'] ,'staff_id' => $staff_id ,'status' => $params['status']]);
        }
        return $this->success($result);
    }


}


